/**
 * 
 */
package qy.jalgotrade.utils;

import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;

/**
 * @author qy
 *
 */
public class FastUtilIntArrayListDeque implements PySpecs.SeqGetItem<Integer> {

	private IntArrayList __values;

	private int __maxLen;

	private int __nextPos;

	/**
	 * 
	 * @param maxLen
	 */
	public FastUtilIntArrayListDeque(int maxLen) {

		assert maxLen > 0 : "Invalid maximum length";
		__maxLen = maxLen;
		__nextPos = 0;
		__values = new IntArrayList();
	}

	/**
	 * 
	 * @return
	 */
	public int getMaxLen() {

		return __maxLen;
	}

	/**
	 * 
	 * @param value
	 */
	public void append(int value) {

		if (__nextPos < __maxLen) {
			__values.add(__nextPos, value);
			__nextPos++;
		} else {
			/*
			 * Shift items to the left and put the last value.
			 * I'm not using np.roll to avoid creating a new array.
			 */
			__values.removeInt(0);
			__values.add(__nextPos - 1, value);
		}
	}

	/**
	 * 
	 * @return
	 */
	public IntList data() {

		// If all values are not initialized, return a portion of the array.
		if (__nextPos < __maxLen) {
			return __values.subList(0, __nextPos);
		} else {
			return __values;
		}
	}

	/**
	 * 
	 * @return
	 */
	public int[] toPrimitiveArray() {

		// If all values are not initialized, return a portion of the array.
		int[] ret = new int[__len__()];
		__values.getElements(0, ret, 0, ret.length);
		return ret;
	}

	/**
	 * 
	 * @param maxLen
	 */
	public void resize(int maxLen) {

		assert maxLen > 0 : "Invalid maximum length";

		IntList lastValues = __values.subList(0, __nextPos);
		int startIdx = lastValues.size() - maxLen;
		if (startIdx > 0) {
			// Create empty, copy last values and swap.
			IntArrayList values = new IntArrayList(lastValues.size());
			values.addAll(startIdx, lastValues);
			__values = values;
		}

		__maxLen = maxLen;
		if (__nextPos >= __maxLen) {
			__nextPos = __maxLen;
		}
	}

	/*
	 * (non-Javadoc)
	 * @see qy.jalgotrade.utils.PySpecs.Len#__len__()
	 */
	@Override
	public int __len__() {

		return __nextPos;
	}

	/*
	 * (non-Javadoc)
	 * @see qy.jalgotrade.utils.PySpecs.SeqGetItem#__getitem__(int)
	 */
	@Override
	public Integer __getitem__(int idx) {

		if (idx < 0) {
			idx += __len__();
		}
		return __values.getInt(idx);
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {

		return __values.toString();
	}
}
